5 Easy SQL INNER JOIN Examples for Beginners 您所在的位置:网站首页 first category name 5 Easy SQL INNER JOIN Examples for Beginners

5 Easy SQL INNER JOIN Examples for Beginners

2024-07-10 20:10| 来源: 网络整理| 查看: 265

Looking for a clear explanation of joins in SQL? Check out these five SQL INNER JOIN examples!

In SQL, INNER JOINs can be a bit difficult for beginners to master. But once you start working with them, you’ll learn they’re very useful! Let’s discuss five examples of SQL INNER JOINs. But first, let’s do a quick review of why JOINs matter.

In relational databases, data is organized and stored within tables. Each table represents a specific type of information. But, oftentimes, you need to analyze data from different tables simultaneously. And this is where JOINs step in.

We encourage you to practice joining tables by following our interactive SQL JOINs course. It includes 93 exercises covering the following topics:

SQL JOIN types. Multiple JOINs. Self-joins, i.e. joining a table with itself. Non-equi JOINs.

So, are you ready to look at some examples of INNER JOIN? Let’s get started!

Bringing Tables Together: Introducing SQL JOIN Operations

SQL JOINs combine data from two or more tables based on matching column values. For instance, you can merge customers’ information with the orders they made or link each product to its suppliers.

SQL JOINs enable you to join data from different tables and extract meaningful information for your specific use case. Check out this SQL JOIN Cheat Sheet to get the overview of different types of JOINs.

An INNER JOIN in SQL combines rows from multiple tables by matching their common column values. When you apply an INNER JOIN to link customer data with their corresponding orders, you'll see a list of customers who have placed at least one order.

In addition to INNER JOIN, SQL also provides other types of joins: LEFT JOIN, RIGHT JOIN, and FULL JOIN. Those joins are called OUTER JOINs. Unlike an INNER JOIN, an OUTER JOIN operation can list rows from both tables, even if there is no match.

Let’s look at an example to better understand the nature of SQL INNER JOINs.

Here is the customers table that stores customer information:

customer_idfirst_namelast_nameemail [email protected] [email protected] [email protected]

And here is the orders table that stores all orders made by the customers:

order_idcustomer_idorder_dateorder_amount 2716/6/2023100.00 2827/7/2023150.00 2918/8/202320.00

The common column (shown in pink) on which the customers and orders tables are joined is the customer_id column.

Now, here’s the query:

SELECT c.customer_id, c.email, o.order_date, o.order_amount FROM customers AS c INNER JOIN orders AS o ON c.customer_id = o.customer_id;

This query joins the customers table (aliased AS c) and the orders table (aliased AS o). These table aliases provide a clear way to inform the database of the source table of each column (using the syntax table_alias.column_name).

These aliases are employed within the ON clause to establish the column for joining tables. We also  use them in the SELECT statement, where two columns are selected from the customers table (c.customer_id and c.email) and another two columns from the orders table (o.order_date and o.order_amount).

Here is the output of the query:

customer_idemailorder_dateorder_amount [email protected]/6/2023100.00 [email protected]/7/2023150.00 [email protected]/8/202320.00

You might observe that the customer with the ID of 3 does not appear in the resulting table. This particular customer hasn’t placed any orders yet; thus, they don’t have any matching records in the orders table.

The INNER JOIN keyword is interchangeable with the JOIN keyword. In other words, when you use JOIN, the database interprets it as a shorthand notation for INNER JOIN.

To learn more about INNER JOINs, check out our article What Is an Inner Join in SQL?.

SQL INNER JOIN Examples in Practice

Let's explore some SQL INNER JOIN examples tailored for beginners. Before jumping into the examples, check out this article on how to practice SQL JOINs.

Example 1: Link Books with Authors

You’ve got two tables that store information about books and authors. Join these tables to see the list of books along with their authors.

Here is the books table:

book_idtitlepublication_yearauthor_id 1Frankenstein181822 2The Time Machine189523 3The Martian201124 42001: A Space Odyssey196825 5Dune196526

The book_id column uniquely identifies each book. And the author_id column assigns an author to each book.

And here is the authors table:

author_idauthor_name 22Mary Shelley 23H. G. Wells 24Andy Weir 25Arthur C. Clarke 26Frank Herbert

The author_id column uniquely identifies each author. And the author_name column stores authors’ full names.

If you want to see book titles and their author names, you can join these tables based on their common column (the author_id column in both tables). Just select title from books and author_name from authors:

SELECT b.title, a.author_name FROM books AS b INNER JOIN authors AS a ON b.author_id = a.author_id;

This is the resulting table:

titleauthor_name FrankensteinMary Shelley The Time MachineH. G. Wells The MartianAndy Weir 2001: A Space OdysseyArthur C. Clarke DuneFrank Herbert

Please note that each book is assigned one author and each author is assigned one book, as there are no duplicate values in the common author_id column. Examine the next example to see what happens if the common column has duplicate values.

Example 2: Assign Products to Categories

You’ve got two tables that store products and product categories. Join these tables to see the list of products along with their categories.

Here is the products table:

product_idproduct_namecategory_id 1Apple22 2Orange22 3Potato23 4Carrot23 5Chocolate24

The product_id column uniquely identifies each product. And the category_id column assigns a category to each product.

And here is the categories table:

category_idcategory_name 22Fruits 23Vegetables 24Snacks

The category_id column uniquely identifies each category. And the category_name column stores full category names.

If you want to see products and their categories, you can join these tables based on their common column, which is the category_id column. Here’s the query:

SELECT p.product_name, c.category_name FROM products AS p INNER JOIN categories AS c ON p.category_id = c.category_id;

This is the resulting table:

product_namecategory_name AppleFruits OrangeFruits PotatoVegetables CarrotVegetables ChocolateSnacks

The categories with IDs of 22 and 23 are assigned to two products each; their names appear twice in the output table.

Example 3: List Doctors and Patients with the Same First Name

You’ve got two tables that store information about doctors and patients. Join these tables to see the list of doctors and patients who share the same first name.

Here is the doctors table:

doctor_idfirst_namelast_name 1SamanthaMonroe 2MelvinFerrell 3AlbieBlake 4RoseBernard 5LouiPeterson

The doctor_id column uniquely identifies each doctor. The other two columns store doctors’ first and last names.

And here is the patients table:

patient_idfirst_namelast_name 23BenWoodward 24SamanthaThomson 25KateDonovan 26AlbieVasquez 27LouiChen

The patient_id column uniquely identifies each patient. The other two columns store patients’ first and last names.

If you want to see the list of doctors and patients who share the same first name, you can join these tables based on the first_name column.

SELECT d.*, p.* FROM doctors AS d INNER JOIN patients AS p ON d.first_name = p.first_name;

Please note that d.* defines all columns from the doctors table and p.* defines all columns from the patients table.

This is the resulting table:

doctor_idfirst_namelast_namepatient_idfirst_namelast_name 1SamanthaMonroe24SamanthaThomson 3AlbieBlake26AlbieVasquez 5LouiPeterson27LouiChen

Thanks to the INNER JOIN operation, you can list only the doctor and patient pairs where the first names are the same.

Example 4: Match People to Suitable Apartments

You’ve got two tables that store information about apartments available for rent and people looking for apartments that fit their price range. Join these tables to see which apartments can be rented by which person.

Here is the apartments table:

apartment_idrent 11000 2700 3500

The apartment_id column uniquely identifies each apartment. And the rent column stores the monthly rent amount.

And here is the persons table:

person_idemailmax_rent [email protected] [email protected] [email protected]

The person_id column uniquely identifies each person who is looking for an apartment to rent. The email column stores their emails and the max_rent column stores the maximum amount of monthly rent they are able to pay for the apartment.

If you want to see which apartments can be rented by which person, you can join these tables based on the rent and max_rent columns:

SELECT p.person_id, p.email, a.apartment_id, a.rent AS apartment_rent FROM apartments AS a INNER JOIN persons AS p ON a.rent < p.max_rent;

Here the match must be made between the rent column of the apartments table and the max_rent column of the persons table, where rent < max_rent.

This is the resulting table:

person_idemailapartment_idapartment_rent [email protected] [email protected] [email protected] [email protected] [email protected] [email protected]

By using the ON clause with the condition containing the



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有